package jvm;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Europa
 * @create 2020-05-29 23:11
 */
public class ReadWrite {

    private volatile Map<Object, Object> map = new HashMap<>(16);
    private ReadWriteLock readWrite = new ReentrantReadWriteLock();
    private Lock lock = new ReentrantLock();

    /**
     * 无锁put
     *
     * @param key   键
     * @param value 值
     */
    public void unlockPut(Object key, Object value) {
        System.out.println(Thread.currentThread().getName() + " 写入 " + key);
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + " 写入完成");
    }

    /**
     * 无锁get
     *
     * @param key 键
     */
    public void unlockGet(Object key) {
        System.out.println(Thread.currentThread().getName() + " 读取到key " + key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName() + " 读取到 " + o);
    }

    /**
     * 读写锁put
     *
     * @param key   键
     * @param value 值
     */
    public void rwLockPut(Object key, Object value) {
        readWrite.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 写入 " + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + " 写入完成");
        } finally {
            readWrite.writeLock().unlock();
        }
    }

    /**
     * 读写锁get
     *
     * @param key 键
     */
    public void rwLockGet(Object key) {
        readWrite.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 读取到key " + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + " 读取到 " + o);
        } finally {
            readWrite.readLock().unlock();
        }
    }

    /**
     * 重入锁put
     *
     * @param key   键
     * @param value 值
     */
    public void lockPut(Object key, Object value) {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 写入 " + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + " 写入完成");
        } finally {
            lock.unlock();
        }
    }

    /**
     * 重入锁get
     *
     * @param key 键
     */
    public void lockGet(Object key) {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 读取到key " + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + " 读取到 " + o);
        } finally {
            lock.unlock();
        }
    }


}
